package com.zhj.lock;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author zhj
 */
@Component
public class RedisLock implements Lock {

    private static final String LOCK_NAME = "redis_lock_stock";

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void lock() {
        while (true) {

            // unlock 未执行会出现死锁，我们可以通过设置过期时间防止死锁
            // Boolean flag = redisTemplate.opsForValue().setIfAbsent("lockName", LOCK_NAME);
            Boolean flag = redisTemplate.opsForValue().setIfAbsent("lockName", LOCK_NAME,15,TimeUnit.SECONDS);
            if (flag) {
                return;
            } else {
                System.out.println("等待获取redis锁");
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        redisTemplate.delete("lockName");
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
